﻿using SqlSugar;
using SqlSugarWebApi.Entity.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace SqlSugarWebApi.DataContext.Services
{

    public class UserService : IUserService
    {
        private readonly SqlSugarClient context;
        public UserService(SqlSugarClient _context)
        {
            context = _context;
        }

        /// <summary>
        ///  查询获取所有的 admin 用户
        /// </summary>
        /// <returns></returns>
        public async Task<List<Admin>> GetAllAdmins()
        {
            //List<Admin> list_admin=await context.Queryable<Admin>().ToListAsync();
            List<Admin> list_admin = await context.SqlQueryable<Admin>("select * from admin").ToListAsync();
            return list_admin;
        }

        /// <summary>
        /// 通过用户名获取指定用户
        /// </summary>
        /// <param name="adminName"></param>
        /// <returns></returns>
        public async Task<Admin> GetAdminByName(string adminName)
        {
            Admin admin = await context.Queryable<Admin>().Where(a => a.AdminName == adminName).SingleAsync();
            return admin;
        }

        public async Task<int> InsertEntity(Admin admin)
        {
            // 添加后返回自增主键（适合主键是自增列的场景）  忽略主键自增字段 
            int newAdminIdAsync = await context.Insertable(admin).ExecuteReturnIdentityAsync();

            //仅执行添加，返回受影响行数（适合非自增主键）
            //int affectedRowsAsync = await context.Insertable(admin).ExecuteCommandAsync();

            return newAdminIdAsync;
        }
    }
}
